Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix/distribution commission #217

Merged
merged 5 commits into from
Jun 28, 2024
Merged

Fix/distribution commission #217

merged 5 commits into from
Jun 28, 2024

Conversation

sh-cha
Copy link
Contributor

@sh-cha sh-cha commented Jun 27, 2024

  • ensure to sort when making decpools & pools
  • add multi staking tests

@sh-cha sh-cha self-assigned this Jun 27, 2024
@sh-cha sh-cha requested a review from a team as a code owner June 27, 2024 07:27
Copy link

coderabbitai bot commented Jun 27, 2024

Walkthrough

Walkthrough

The updates primarily focus on enhancing the distribution module in several areas: adjusting bond denoms and reward weights for validators, optimizing decimal and pool sorting functionalities, and refining the commission withdrawal process. Additionally, there are multiple new test cases aimed at ensuring the correctness of these changes.

Changes

File Change Summary
x/distribution/keeper/allocation_test.go Introduced new bond denoms and updated reward, voting power weights.
x/distribution/keeper/common_test.go Added VotingPowerKeeper struct and associated methods, updated keepers struct initialization.
x/distribution/keeper/keeper.go Added a line in WithdrawValidatorCommission for truncating commissions.
x/distribution/keeper/validator.go Modified IncrementValidatorPeriod to directly add a new DecPool instance.
x/distribution/types/dec_pool.go Improved sorting functionality, introduced isSorted method, refined various other methods.
x/distribution/types/dec_pool_test.go Added comprehensive test cases for DecPools functionality.
x/distribution/types/pool.go Refactored Pools type methods, introduced NewPools constructor; enhanced sorting, validation functionalities.
x/distribution/types/pool_test.go Added thorough test cases for pool-related functionalities.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Validator
    participant Keeper
    participant Rewards
    User->>Validator: Stake tokens in various denoms
    Validator->>Keeper: Set bond denoms and weights
    Keeper->>Rewards: Allocate rewards based on new weights
    Rewards->>Validator: Distribute rewards
    Validator->>User: Rewards received
Loading

Poem

🐰 A rabbit’s leap, the tokens spread,
In pools and denoms they find their bed.
Rewards now flow, weights redefined,
Commission’s clear, all aligned.
Sorting done with utmost care,
Validators, now, rewards they share. 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

codecov bot commented Jun 27, 2024

Codecov Report

Attention: Patch coverage is 80.00000% with 14 lines in your changes missing coverage. Please review.

Project coverage is 40.22%. Comparing base (a877b19) to head (ecd11b2).
Report is 12 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main     #217      +/-   ##
==========================================
+ Coverage   38.97%   40.22%   +1.25%     
==========================================
  Files         251      258       +7     
  Lines       24165    24617     +452     
==========================================
+ Hits         9418     9903     +485     
+ Misses      13233    13183      -50     
- Partials     1514     1531      +17     
Files Coverage Δ
x/distribution/keeper/keeper.go 69.53% <100.00%> (+0.20%) ⬆️
x/distribution/keeper/validator.go 43.38% <100.00%> (+0.31%) ⬆️
x/distribution/types/dec_pool.go 85.00% <68.18%> (+85.00%) ⬆️
x/distribution/types/pool.go 80.25% <84.78%> (+80.25%) ⬆️

... and 30 files with indirect coverage changes

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 170cc34 and ecd11b2.

Files selected for processing (9)
  • x/distribution/keeper/allocation_test.go (7 hunks)
  • x/distribution/keeper/common_test.go (5 hunks)
  • x/distribution/keeper/delegation_test.go (23 hunks)
  • x/distribution/keeper/keeper.go (1 hunks)
  • x/distribution/keeper/validator.go (1 hunks)
  • x/distribution/types/dec_pool.go (5 hunks)
  • x/distribution/types/dec_pool_test.go (1 hunks)
  • x/distribution/types/pool.go (7 hunks)
  • x/distribution/types/pool_test.go (1 hunks)
Files not summarized due to errors (1)
  • x/distribution/keeper/delegation_test.go: Error: Message exceeds token limit
Files not reviewed due to errors (1)
  • x/distribution/keeper/keeper.go (no review received)
Additional comments not posted (31)
x/distribution/types/pool_test.go (1)

1-268: Test cases for pool functionality are comprehensive and well-constructed.

The tests cover various scenarios including equality, addition, and subtraction, which are crucial for ensuring the robustness of the Pools methods. Ensure all new logic is covered, and consider adding more edge cases if necessary.
[APROVED]

x/distribution/types/dec_pool_test.go (15)

35-82: Initialization logic in SetupSuite appears comprehensive.

The method properly initializes various denominations and amounts, ensuring a wide range of test scenarios are covered.


84-102: Proper testing of DecPool equality.

The TestIsEqualPool method correctly tests the IsEqual method of DecPool using varied scenarios, ensuring robustness in equality checks.


104-117: Effective testing of pool emptiness.

The TestIsEmptyPool method effectively checks the emptiness of pools using clear and concise test cases.


119-140: Thorough testing of the addition of DecPools.

The TestAddPool method includes comprehensive test cases that cover normal operations and error conditions effectively.


142-163: Robust testing of the subtraction of DecPools.

The TestSubPool method is well-structured and tests the subtraction functionality thoroughly, including error scenarios.


165-177: Effective validation of DecPools sorting upon creation.

The TestNewPoolsSorted method correctly ensures that new DecPools are sorted, which is crucial for performance and correctness in subsequent operations.


179-196: Comprehensive testing of adding multiple DecPools.

The TestAddPools method effectively tests the addition of multiple DecPools, ensuring correct and optimized handling of complex scenarios.


198-215: Robust testing of subtracting multiple DecPools.

The TestSubPools method thoroughly tests the subtraction of multiple DecPools, ensuring the functionality is reliable even in complex scenarios.


217-229: Effective detection of negative values in DecPools.

The TestIsAnyNegativePools method accurately identifies negative values in DecPools, which is essential for maintaining integrity in financial operations.


232-248: Accurate testing of coin retrieval from DecPools.

The TestCoinsOfPools method effectively tests the retrieval of coins based on denominations, ensuring accurate and efficient access to pool values.


250-263: Proper testing of emptiness for multiple DecPools.

The TestIsEmptyPools method correctly evaluates the emptiness of multiple DecPools, ensuring the functionality works as expected across different scenarios.


265-280: Thorough testing of equality for multiple DecPools.

The TestIsEqualPools method provides a comprehensive test of the equality functionality for multiple DecPools, ensuring accurate comparisons.


282-295: Effective testing of summing multiple DecPools.

The TestSumPools method successfully tests the summing of multiple DecPools, ensuring the operation is performed correctly and efficiently.


297-320: Robust testing of truncating decimal values in DecPools.

The TestTruncatePools method effectively tests the truncation of decimal values, ensuring precision is managed correctly in financial operations.


322-344: Effective testing of intersecting multiple DecPools.

The TestIntersectPools method accurately tests the intersection functionality for multiple DecPools, ensuring it works correctly for complex scenarios.

x/distribution/keeper/common_test.go (2)

Line range hint 192-422: Comprehensive setup for testing multiple keepers.

The createTestInput function effectively sets up a complex test environment, initializing multiple keepers and ensuring their interactions are correctly configured.


610-613: Proper initialization of TestVotingPowerKeeper with default weights.

The NewTestVotingPowerKeeper method correctly initializes the TestVotingPowerKeeper with appropriate default weights, ensuring it is ready for use in tests.

x/distribution/keeper/allocation_test.go (4)

156-197: Consistent addition of 'aaa' denom across multiple test configurations.

Ensure the new denom 'aaa' is properly handled in all relevant test scenarios where SetBondDenoms is used.

Verification successful

Consistent addition of 'aaa' denom across multiple test configurations.

The new denom 'aaa' is properly handled in all relevant test scenarios where SetBondDenoms is used.

  • x/distribution/keeper/allocation_test.go
  • x/distribution/keeper/delegation_test.go
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that the new denom 'aaa' is properly handled across all test cases.
rg --type go $'SetBondDenoms\(\.\.\.\)' x/distribution/keeper/allocation_test.go

Length of output: 81



Script:

#!/bin/bash
# Description: Verify that the new denom 'aaa' is properly handled across all test cases.
rg --type go 'SetBondDenoms\('

Length of output: 2066


81-81: Proper addition of 'aaa' denom to voting power weights.

Verify that the new voting power weight for 'aaa' is consistently used in scenarios that depend on SetVotingPowerWeights.

Verification successful

Proper addition of 'aaa' denom to voting power weights.

The new voting power weight for 'aaa' is consistently used in both delegation_test.go and allocation_test.go.

  • x/distribution/keeper/delegation_test.go
  • x/distribution/keeper/allocation_test.go
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that the new voting power weight for 'aaa' is consistently used.
rg --type go $'SetVotingPowerWeights\(\.\.\.\)' x/distribution/keeper/allocation_test.go

Length of output: 89



Script:

#!/bin/bash
# Locate the definition of SetVotingPowerWeights in the repository
ast-grep --lang go --pattern 'func SetVotingPowerWeights($_, $_) { $$$ }'

# Locate all usages of SetVotingPowerWeights across the repository
rg 'SetVotingPowerWeights\('

Length of output: 2897


Line range hint 170-213: Proper addition of 'aaa' denom to voting power weights in multiple test scenarios.

Verify that the new voting power weight for 'aaa' is consistently used in scenarios that depend on SetVotingPowerWeights.

Verification successful

Proper addition of 'aaa' denom to voting power weights in multiple test scenarios.

The new voting power weight for 'aaa' is consistently used across various test files, confirming the changes have been properly integrated.

  • Files Verified:
    • x/distribution/keeper/allocation_test.go
    • x/distribution/keeper/delegation_test.go
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that the new voting power weight for 'aaa' is consistently used.
rg --type go $'SetVotingPowerWeights\(\.\.\.\)' x/distribution/keeper/allocation_test.go

Length of output: 89



Script:

#!/bin/bash
# Description: Verify that the new voting power weight for 'aaa' is consistently used across the entire codebase.
rg --type go 'SetVotingPowerWeights' 

Length of output: 2827


Line range hint 65-78: Addition of 'aaa' denom to bond denoms is consistent and well-implemented.

Ensure that the new denom 'aaa' is properly handled in all relevant test scenarios where SetBondDenoms is used.

x/distribution/keeper/delegation_test.go (9)

21-36: Approved: Updates to bond denominations and reward weights in TestCalculateRewardsBasic.

The addition of the "aaa" denomination and corresponding reward weights are well-integrated into the test setup. This change should help ensure that the new denomination is properly handled in reward calculations.

Also applies to: 38-44


145-159: Approved: Proper setup for testing rewards after slashing in TestCalculateRewardsAfterSlash.

The changes to include the "aaa" denomination and adjust reward weights are crucial for testing the impact of slashing under new conditions. The test logic is sound and aligns well with the expected outcomes described in the PR.

Also applies to: 161-168


270-284: Approved: Configuration for multiple slashes scenario in TestCalculateRewardsAfterManySlashes.

The inclusion of multiple slashes in this test function is a good stress test for the reward calculation logic under adverse conditions. The setup changes are consistent and necessary for the intended test coverage.

Also applies to: 286-293


428-442: Approved: Setup for multi-delegator reward calculation in TestCalculateRewardsMultiDelegator.

The adjustments to include new denominations and corresponding reward weights are crucial for accurately testing the reward distribution among multiple delegators. This is a key aspect of ensuring the robustness of the distribution logic.

Also applies to: 444-451


570-584: Approved: Basic reward withdrawal setup in TestWithdrawDelegationRewardsBasic.

The changes to include the "aaa" denomination in the setup are important for testing the basic functionality of reward withdrawals. This ensures that the system behaves as expected when new denominations are involved.

Also applies to: 586-593


675-689: Approved: Zero rewards withdrawal test setup in TestWithdrawDelegationZeroRewards.

Including tests for zero rewards is an important part of ensuring robustness in the rewards system, particularly with the introduction of new denominations. The setup changes are appropriate and necessary for this test scenario.

Also applies to: 691-698


745-759: Approved: Setup for testing multiple slashes in the same block in TestCalculateRewardsAfterManySlashesInSameBlock.

Testing multiple slashes in the same block is a critical scenario for understanding the robustness of the reward calculation system. The setup changes are well thought out and align with the objectives of the test.

Also applies to: 761-768


892-906: Approved: Complex test setup for multiple delegators and slashes in TestCalculateRewardsMultiDelegatorMultiSlash.

The setup for this function is comprehensive, covering multiple delegators and multiple slashes, which is essential for testing the system's handling of complex scenarios. The changes are well-executed and align with the test's objectives.

Also applies to: 908-915


1056-1070: Approved: Multi-delegator, multi-withdrawal test setup in TestCalculateRewardsMultiDelegatorMultWithdraw.

The setup for testing multiple withdrawals by multiple delegators is crucial for ensuring the distribution system's functionality under varied operational scenarios. The changes are appropriate and align with the testing goals.

Also applies to: 1072-1079

} else {
current = append(current, customtypes.NewDecPool(token.Denom, rewardCoins.QuoDecTruncate(math.LegacyNewDecFromInt(token.Amount))))
current = current.Add(customtypes.NewDecPool(token.Denom, rewardCoins.QuoDecTruncate(math.LegacyNewDecFromInt(token.Amount))))
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tip

Codebase Verification

Inconsistent use of division methods in financial calculations.

The QuoDecTruncate method is only used in one instance, while other instances use QuoDec and Div without truncation. This inconsistency could lead to different rounding behaviors and potential issues in financial calculations. Review and standardize the use of division methods across the codebase.

  • x/mstaking/keeper/delegation_test.go
  • x/move/ante/gas_prices_test.go
  • x/move/ante/gas_prices.go
Analysis chain

Approved change in reward calculation method.

The use of QuoDecTruncate for calculating the reward distribution is a safer choice to prevent rounding errors. Ensure this change aligns with other financial calculations across the system.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that QuoDecTruncate is used consistently across similar financial calculations.

# Test: Search for similar usages of division in financial calculations.
rg --type go $'QuoDecTruncate'

Length of output: 194



Script:

#!/bin/bash
# Description: Search for other methods of division in financial calculations to identify inconsistencies.

# Test: Search for other division methods in financial calculations.
rg --type go 'QuoDec\(|QuoDecTruncate\(|Div\('

Length of output: 1727

Comment on lines +14 to +17
// NewPools creates a new Pools instance
func NewPools(pools ...Pool) Pools {
return removeZeroPools(pools).Sort()
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Enhancements to pool handling and safety checks approved.

The changes ensure that pools are always sorted and zero pools are removed before operations, which enhances safety and consistency. Consider adding comments explaining why sorting is necessary before operations like addition.

+ // Ensure pools are sorted to maintain consistency and prevent errors in set operations.
+ // Removing zero pools to clean up the data before processing.

Also applies to: 34-65, 205-222

@@ -19,7 +19,7 @@
decPools = append(decPools, NewDecPool(p.Denom, sdk.NewDecCoinsFromCoins(p.Coins...)))
}

return decPools
return decPools.Sort()
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Enhancements to decimal pool handling and safety checks approved.

The changes ensure that decimal pools are always sorted and zero pools are removed before operations, which enhances safety and consistency. Consider adding comments explaining why sorting is necessary before operations like addition, similar to pool.go.

+ // Ensure decimal pools are sorted to maintain consistency and prevent errors in set operations.
+ // Removing zero decimal pools to clean up the data before processing.

Also applies to: 41-283

Copy link
Member

@beer-1 beer-1 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@beer-1 beer-1 merged commit dce66e2 into main Jun 28, 2024
7 checks passed
@beer-1 beer-1 deleted the fix/distribution-commission branch June 28, 2024 05:30
@coderabbitai coderabbitai bot mentioned this pull request Oct 24, 2024
11 tasks
RiccardoM pushed a commit to milkyway-labs/milkyway that referenced this pull request Nov 13, 2024
## Description

Closes: MILK-104

This PR cherry picks the changes made by the Initia team to `Pools` and
`DecPools` in this [PR](initia-labs/initia#217).

---

### Author Checklist

*All items are required. Please add a note to the item if the item is
not applicable and
please add links to any relevant follow up issues.*

I have...

- [x] included the correct [type
prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json)
in the PR title
- [ ] added `!` to the type prefix if API or client breaking change
- [ ] targeted the correct branch (see [PR
Targeting](https://github.com/milkyway-labs/milkyway/blob/master/CONTRIBUTING.md#pr-targeting))
- [ ] provided a link to the relevant issue or specification
- [ ] followed the guidelines for [building
modules](https://docs.cosmos.network/v0.44/building-modules/intro.html)
- [ ] included the necessary unit and integration
[tests](https://github.com/milkyway-labs/milkyway/blob/master/CONTRIBUTING.md#testing)
- [ ] added a changelog entry to `CHANGELOG.md`
- [ ] included comments for [documenting Go
code](https://blog.golang.org/godoc)
- [ ] updated the relevant documentation or specification
- [x] reviewed "Files changed" and left comments if necessary
- [x] confirmed all CI checks have passed

### Reviewers Checklist

*All items are required. Please add a note if the item is not applicable
and please add
your handle next to the items reviewed if you only reviewed selected
items.*

I have...

- [ ] confirmed the correct [type
prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json)
in the PR title
- [ ] confirmed `!` in the type prefix if API or client breaking change
- [ ] confirmed all author checklist items have been addressed
- [ ] reviewed state machine logic
- [ ] reviewed API design and naming
- [ ] reviewed documentation is accurate
- [ ] reviewed tests and test coverage
- [ ] manually tested (if applicable)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants